<?php

/**
 *
 * @todo: 是否实现该类的单例模式
 */

namespace App;

class Logger
{
    static $buffer = array();
    private $async = TRUE;
    private $file = '/tmp/php_runtime.log';

    function __construct($file = '', $async = TRUE)
    {
        if (!empty($file) && is_file($file))
        {
            $this->file = $file;
        }
        if ($async)
        {
            register_shutdown_function(array($this, 'shutdown'));
        }

        $this->async = $async;
    }

    protected function shutdown()
    {
        //同步日志到disk,清理资源
        $logs = implode('', Logger::$buffer);
        file_put_contents($this->file, $logs, FILE_APPEND | LOCK_EX);
    }

    private function package($info, $level = 'INFO')
    {
        return "[{$level}]\t[" . date('Y-m-d H:i:s') . "]\t" . $info . "\n";
    }

    private function writeBuffer($info)
    {
        Logger::$buffer[] = $info;
    }

    private function write($info)
    {
        //直接写入硬盘
    }

    public function __call($method, $args)
    {
        $info = $this->package($args[0], strtoupper($method));
        if ($this->async)
        {
            $this->writeBuffer($args[0]);
        }
        else
        {
            $this->write($args[0]);
        }
    }
}

/**
 * @example:
 *  $logger = new Logger();
 *  $logger->info('infofinfofafdsa');
 *  $logger->warn('这里出现了警告');
 */

/*
Level	描述	例子
emerg	紧急(系统无法使用)	"Child cannot open lock file. Exiting"
alert	必须立即采取措施	"getpwuid: couldn't determine user name from uid"
crit	致命情况	"socket: Failed to get a socket, exiting child"
error	错误情况	"Premature end of script headers"
warn	警告情况	"child process 1234 did not exit, sending another SIGHUP"
notice	一般重要情况	"httpd: caught SIGBUS, attempting to dump core in ..."
info	普通信息	"Server seems busy, (you may need to increase StartServers, or Min/MaxSpareServers)..."
debug	调试信息	"Opening config file ..."
*/
?>